package com.itboye.app.mian.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.CameraPopupWindow;
import com.itboye.core.utils.ImageCompress;
import com.itboye.core.utils.ImageUpdate;
import com.itboye.core.utils.ImageUpdate.OnUpdatelistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.jmsfhz.R;
import com.itboye.jmsfhz.cliptools.ClipActivity;

public class ShenFenRenZhengActivity extends BaseActivity implements
		OnUpdatelistener {
	private CameraPopupWindow cameraPopupWindow;

	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	// 获取日期格式器对象

	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择

	private String picture_name;
	private String fileName;
	private String localSelectPath;

	private ImageView imgZhiZhao;

	private RelativeLayout layoutShang;

	private TextView tvZhiZhao;
	private Button btnPush;
	private String url;
	public static String AVARTACTION = "com.itboye.avart";
	private String RENZHENG;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_shenfenrenzheng;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		IntentFilter intentFilterAvart = new IntentFilter(AVARTACTION);
		this.registerReceiver(avartBroadcastReceiver, intentFilterAvart);
		RENZHENG = (String) SPUtils
				.get(this, null, SpPublicParams.RENZHENG, "");
		if (RENZHENG.equals("0")) {
			tvZhiZhao.setVisibility(View.VISIBLE);
		} else if (RENZHENG.equals("1")) {
			try {

				XImageLoader.load((String) SPUtils.get(this, null,
						SpPublicParams.IMAGE_URL, ""), imgZhiZhao);
				tvZhiZhao.setVisibility(View.GONE);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		url = (String) SPUtils.get(ShenFenRenZhengActivity.this, null,
				SpPublicParams.IMAGE_URL, "");
	
		layoutShang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				cameraPopupWindow = new CameraPopupWindow(
						ShenFenRenZhengActivity.this, onclicklister);
				cameraPopupWindow.showAtLocation(arg0, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});
		btnPush.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// XImageLoader.load(
				// (String) SPUtils.get(ShenFenRenZhengActivity.this, null,
				// SpPublicParams.IMAGE_URL, ""),
				// imgZhiZhao);
				if (url == "" || url == null) {
					ByAlert.alert("保存失败！");
				} else {
					ByAlert.alert("成功！");
					XImageLoader.load(url, imgZhiZhao);
					finish();
				}

			}
		});
	}

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					ByAlert.alert("请确认已经插入SD卡");
				}
				break;
			case R.id.pick_image:
				// new PhotoSelectFragment(new PhotoSelect(),
				// 6 - imgContainer.getChildCount() + 1).show(
				// getSupportFragmentManager(), null);
				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				return;
			}

			picture_name = android.text.format.DateFormat.format(
					"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
					+ ".jpg";
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
			File file = new File("/sdcard/Image/");
			file.mkdirs();// 创建文件夹
			fileName = "/sdcard/Image/" + picture_name;

			FileOutputStream b = null;
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ImageUpdate.getInstance().execute(fileName, this);
			cameraPopupWindow.dismiss();
		} else if (requestCode == PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
				localSelectPath = getRealPathFromURI(selectedImage);
				localSelectPath = ImageCompress.compress(localSelectPath);
				Intent intent2 = new Intent(ShenFenRenZhengActivity.this,
						ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			}

		} else if (requestCode == IMAGE_COMPLETE) {
			ImageUpdate.getInstance().execute(localSelectPath, this);
			cameraPopupWindow.dismiss();
		}
	};

	public static final int IMAGE_COMPLETE = 6; // 结果

	/**
	 * This method is used to get real path of file from from uri<br/>
	 * http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-
	 * captured-from-camera
	 * 
	 * @param contentUri
	 * @return String
	 */
	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			@SuppressWarnings("deprecation")
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	BroadcastReceiver avartBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			XImageLoader.load((String) SPUtils.get(
					ShenFenRenZhengActivity.this, null,
					SpPublicParams.IMAGE_URL, ""), imgZhiZhao);

		};
	};

	@Override
	public void OnSuccess(String resultData) {
		// tvZhiZhao.setVisibility(View.GONE);
		String time = String.valueOf((int) (Math.random() * 10));
		Toast.makeText(getApplicationContext(), "上传成功", 0).show();
		SPUtils.put(this, null, SpPublicParams.IMAGE_URL, GlobalConfig.SHENFEN
				+ resultData + "&random=" + time);
		XImageLoader.load(
				(String) SPUtils.get(this, null, SpPublicParams.IMAGE_URL, ""),
				imgZhiZhao);

	}

	@Override
	public void OnError(String resultData) {

		Toast.makeText(getApplicationContext(), resultData, 0).show();
		tvZhiZhao.setVisibility(View.VISIBLE);

	}

	public void onImageBack(View view) {
		this.finish();
	}
}
